package com.asia5b.a5mall.member.fragment

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import android.view.Gravity
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.member.adapter.RegionContentAdapter
import com.asia5b.a5mall.member.adapter.RegionTabAdapter
import com.asia5b.a5mall.member.databinding.DialogSelectregion2Binding
import com.asia5b.a5mall.middleware.base.SimpleDialogFragment
import com.asia5b.a5mall.middleware.logic.viewmodel.member.SelectRegionDFVM
import com.asia5b.a5mall.middleware.model.member.AddressModel
import com.asia5b.a5mall.middleware.model.member.RegionModel
import com.asia5b.a5mall.middleware.model.bean.TabRegionBean
import com.asia5b.a5mall.middleware.widget.OnViewPagerListener
import kotlinx.android.synthetic.main.dialog_selectregion2.*

/**
 * Created by zhangyuncai on 2019/12/31.
 */
@Route(path = ActCons.SelectRegion2DF)
class SelectRegion2DF : SimpleDialogFragment<SelectRegionDFVM, DialogSelectregion2Binding>() {

    override val viewModelClazz: Class<SelectRegionDFVM>
        get() = SelectRegionDFVM::class.java

    override fun getDataBinding(container: ViewGroup?): DialogSelectregion2Binding {
        if (arguments != null && requireArguments().containsKey("selectAddressModel")) {
            selectAddressModel = requireArguments().getSerializable("selectAddressModel") as AddressModel
        }
        return DialogSelectregion2Binding.inflate(layoutInflater,container,false)
    }

    var selectAddressModel: AddressModel? = null

    //tab区
    val tabDatas = arrayListOf<TabRegionBean>()
    val tabRecyclerView by lazy { rv_region_tab }
    val tabAdapter by lazy { RegionTabAdapter(tabDatas) }

    //内容区
    val contentRecyclerView by lazy { rv_region_content }
    val contentLayoutManager by lazy { LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false) }
    val contentAdapter by lazy {
        RegionContentAdapter(tabDatas) { selectRegionModel ->
            tabDatas.get(tabAdapter.selectPosition).selectRegionModel = selectRegionModel
            val selectPosition = tabAdapter.selectPosition
            for (index in tabDatas.size - 1 downTo 0) {
                if (index > selectPosition) {
                    tabDatas.removeAt(index)
                }
            }
            tabAdapter.notifyDataSetChanged()
            refreshContentView()
            if (selectRegionModel.typeId < 4) {
                mViewModel.loadRegion(selectRegionModel.id)
            } else {
                submit()
            }
        }
    }


    override fun initView() {

        tabRecyclerView.run {
            layoutManager = LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false)
            adapter = tabAdapter
        }
        contentRecyclerView.run {
            layoutManager = contentLayoutManager
            adapter = contentAdapter
        }
        val pagerSnapHelper = PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(contentRecyclerView)
        contentRecyclerView.addOnScrollListener(object : OnViewPagerListener(pagerSnapHelper) {
            override fun onPageSelected(position: Int, isIdle: Boolean) {
                tabAdapter.selectPosition = position
                tabAdapter.notifyDataSetChanged()
                if (isIdle) {
                }
            }
        })
    }

    /**
     * content刷新
     */
    fun refreshContentView() {
        contentAdapter.notifyDataSetChanged()
        contentRecyclerView.scrollToPosition(tabAdapter.selectPosition)
    }


    override fun initData() {
        if (selectAddressModel?.countryId ?: 0 == 0) {
            mViewModel.loadRegion(0)
        } else {
            mViewModel.loadAllRegion(tabDatas, selectAddressModel!!)
        }
    }


    override fun initEvent() {
        tabAdapter.setOnItemClickListener { adapter, view, position ->
            tabAdapter.selectPosition = position
            tabAdapter.notifyDataSetChanged()
            refreshContentView()
        }
        tv_region_sure.setOnClickListener {
            submit()
        }
    }

    fun submit() {
        var selectAddressModel2 = AddressModel()
        for ((index, tabData) in tabDatas.withIndex()) {
            if (tabData.selectRegionModel == null) {
//                callBack?.callback(null)
                break
            }
            val regionModel = tabData.selectRegionModel!!
            if (index == 0) {//选中的国家
                selectAddressModel2.countryId = regionModel.id
                selectAddressModel2.countryName = regionModel.name
            } else if (index == 1) {//选中的州
                selectAddressModel2.provinceId = regionModel.id
                selectAddressModel2.provinceName = regionModel.name
            } else if (index == 2) {//选中的市
                selectAddressModel2.cityId = regionModel.id
                selectAddressModel2.cityName = regionModel.name
            } else if (index == 3) {//选中的区
                selectAddressModel2.townId = regionModel.id
                selectAddressModel2.townName = regionModel.name
            }
        }
//        callBack?.callback(selectAddressModel2)
        mSureClick?.invoke(selectAddressModel2)
        dismiss()
    }


    override val gravity: Int
        get() = Gravity.BOTTOM

    override val heightPercent: Double
        get() = 0.5

     fun renderRegion(data: ArrayList<RegionModel>, type: Int) {
        tabDatas.add(TabRegionBean().apply {
            this.contentRegionModelList = data
        })
        tabAdapter.selectPosition = tabDatas.size - 1
        tabAdapter.notifyDataSetChanged()

        refreshContentView()
    }

    override fun startObserver()
    {
        mViewModel.loadAllRegionResultLiveData.observe(this, Observer {
            loadAllRegionResult()
        })
        mViewModel.loadRegionErrorLiveData.observe(this, Observer {
            loadRegionError()
        })
        mViewModel.renderRegionLiveData.observe(this, Observer {
            renderRegion(it,0)
        })
    }

     fun loadAllRegionResult() {
        tabAdapter.selectPosition = tabDatas.size - 1
        tabAdapter.notifyDataSetChanged()

        refreshContentView()
    }

     fun loadRegionError() {
        selectAddressModel=null
        mViewModel.loadRegion(0)
    }

}